package com.kyexpress.common.hrinterview.provider.controller;

import com.kyexpress.common.hrinterview.api.model.Employee;
import com.kyexpress.common.hrinterview.api.model.EmployeeUpload;
import com.kyexpress.common.hrinterview.provider.service.EmployeeService;
import com.kyexpress.common.hrinterview.provider.service.EmployeeUploadService;
import com.kyexpress.common.hrinterview.provider.utils.ErrorEnum;
import com.kyexpress.common.hrinterview.provider.utils.Tools;
import com.kyexpress.common.hrinterview.provider.utils.UploadTypeNameEnum;
import com.kyexpress.framework.model.ResponseData;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;

@RestController
public class FileController {
    private static final Logger logger = LoggerFactory.getLogger(FileController.class);
    @Autowired
    private EmployeeUploadService employeeUploadService;
    @Autowired
    private EmployeeService employeeService;
    @RequestMapping(value = "/greeting",method = RequestMethod.POST)
    public String greeting(@RequestParam(value="name", required=false, defaultValue="World") String name, Model model) {
        model.addAttribute("name", name);
        return "greeting";
    }
    /**
     * 文件上传相关代码
     */
    @RequestMapping(value = "upload",method = RequestMethod.POST)
    public ResponseData upload(@RequestParam("file") MultipartFile file,@RequestParam("employeeid") Long employeeid) {
        ResponseData result = new ResponseData();
        if (file.isEmpty()) {
            ErrorEnum.FileNameNotNull.initResponseData(result);
            return result;
        }
        /**
         * 获取文件名
          */
        String fileName = file.getOriginalFilename();
        logger.info("上传的文件名为：" + fileName);
        /**
         *  获取文件的后缀名
          */
        String suffixName = fileName.substring(fileName.lastIndexOf("."));
        logger.info("上传的后缀名为：" + suffixName);
        /**
         * 文件上传后的路径
          */
        String filePath = Tools.FILE_PATH + employeeid+"/";
        /**
         *  解决中文问题，liunx下中文路径，图片显示问题
          */
         fileName = Tools.randomUUID() + suffixName;
        File dest = new File(filePath + fileName);
        /**
         * 检测是否存在目录
          */
        if (!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        FileOutputStream out = null;
        InputStream in = null;
        try {
            out = new FileOutputStream(dest);
            in = file.getInputStream();
            byte[] buffer = new byte[1024];
            int len = 0;
            while ((len = in.read(buffer)) > 0){
                out.write(buffer,0,len);
            }
            result.setData(fileName).ok();
            return result;
        } catch (IllegalStateException e) {
            logger.error("FileController.upload : "+e);
            ErrorEnum.FileIOException.initResponseData(result);
            return result;
        } catch (IOException e) {
            logger.error("FileController.upload : "+e);
            ErrorEnum.FileIOException.initResponseData(result);
            return result;
        }finally {
            try {
                out.flush();
                in.close();
                out.close();
            }catch(IOException ioe){
                logger.error("FileController.upload : "+ioe);
                ErrorEnum.FileIOColse.initResponseData(result);
                return result;
            }
        }
    }

    /**
     * 文件批量打包下载
     */
    @RequestMapping(value = "downloadZipFile",method = RequestMethod.POST)
    public ResponseData downloadZipFile(@RequestBody EmployeeUpload employeeUpload, HttpServletRequest request, HttpServletResponse response) {
        response.setContentType("text/html;charset=UTF-8");
        Long employeeid = employeeUpload.getEmployeeid();
        ResponseData result = new ResponseData();
        if(employeeid == null){
            ErrorEnum.FileEmployeeIdNotNull.initResponseData(result);
            return result;
        }
        EmployeeUpload vo = new EmployeeUpload();
        vo.setEmployeeid(employeeid);
        Employee employee = employeeService.get(employeeid);
        if(employee == null){
            ErrorEnum.EmployeeInfoNotNull.initResponseData(result);
            return result;
        }
        List<EmployeeUpload> lists = this.employeeUploadService.selectAll(vo);
        if(lists == null || lists.size() <= 0){
            ErrorEnum.EmployeeUploadFileInfoNotNull.initResponseData(result);
            return result;
        }
        int errorCode = outPutStream(request, response, lists,employee.getId(),employee.getName());
        if(errorCode == 1){
            ErrorEnum.FileNameNotNull.initResponseData(result);
            return result;
        }else if(errorCode == 2){
            ErrorEnum.FileIOColse.initResponseData(result);
            return result;
        }
        result.setData("/temp/"+employee.getName()+".zip").ok();
        return result;
    }

    /**
     * 生成压缩文件并将文件发送前端
     * @param request
     * @param response
     * @param lists
     * @param employeeid
     * @throws FileNotFoundException
     * @throws IOException
     */
    private int outPutStream(HttpServletRequest request, HttpServletResponse response, List<EmployeeUpload> lists,Long employeeid,String name){
        int errorCode = 0;
        String zipAddress = Tools.FILE_PATH +"temp/"+name+".zip";
        //ZIP打包
        File zipFile = new File(zipAddress);
        /**
         * 检测是否存在目录
         */
        if (!zipFile.getParentFile().exists()) {
            zipFile.getParentFile().mkdirs();
        }
        if(zipFile.exists()){
            zipFile.delete();
        }
        byte[] buf = new byte[1024];
        int len;
        ZipOutputStream zout = null;
//        FileInputStream zipInput = null;
//        OutputStream output = null;
        try {
            zout = new ZipOutputStream(new FileOutputStream(zipFile));
            for (EmployeeUpload employeeUpload : lists) {
                File temp = new File(Tools.FILE_PATH + employeeUpload.getFileUrl());
                if (!temp.exists() || UploadTypeNameEnum.QRcode.getCode().equals(employeeUpload.getTypeName())) {
                    continue;
                }
                FileInputStream in = new FileInputStream(temp);
                System.out.println("fileName " + temp.getName()+"   "+temp.getName().substring(temp.getName().lastIndexOf(".")));
                String suffixName = temp.getName().substring(temp.getName().lastIndexOf("."));
                String dd = (employeeUpload.getFileName() != null && employeeUpload.getFileName().length() >=1) ? employeeUpload.getFileName() : "fileName" + suffixName ;
                System.out.println("fileName " + dd);
                zout.putNextEntry(new ZipEntry(dd));
                while ((len = in.read(buf)) > 0) {
                    zout.write(buf, 0, len);
                }
                zout.closeEntry();
                try {
                    in.close();
                } catch (IOException e) {
                    logger.error("FileController.upload : "+e);
                    errorCode = 2;
                }
            }
//            zout.close();
            //下载ZIP
//            zipInput = new FileInputStream(zipFile);
//            output = response.getOutputStream();
//            response.setContentType("application/octet-stream");
//            response.setHeader("Content-Disposition", "attachment; filename=" + name + ".zip");
//            response.setHeader("contentType", "text/html;charset=UTF-8");
//            while ((len = zipInput.read(buf)) != -1) {
//                output.write(buf, 0, len);
//            }

        }catch (FileNotFoundException e){
            logger.error("FileController.upload : "+e);
            errorCode = 1;
        }catch (IOException e){
            logger.error("FileController.upload : "+e);
            errorCode = 2;
        }
        finally {
            try {
                  zout.close();
//                zipInput.close();
//                output.flush();
                //删除压缩包
//                zipFile.delete();
            } catch (IOException e) {
                logger.error("FileController.upload : "+e);
            }
        }
        return errorCode;
    }

}
